package com.denlaku.longan.service.impl;

import com.denlaku.longan.Const;
import com.denlaku.longan.anno.RequiredTx;
import com.denlaku.longan.config.LonganProperties;
import com.denlaku.longan.qo.Query;
import com.denlaku.longan.repository.ResourceRepository;
import com.denlaku.longan.service.ResourceService;
import com.denlaku.longan.vo.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author tianx
 */
@Service
public class ResourceServiceImpl implements ResourceService {
	@Autowired
	private ResourceRepository resourceRepository;

	@Autowired
	private LonganProperties longanProperties;

	@Override
	@RequiredTx
	public void add(Resource resource) {
		resourceRepository.add(resource);
	}

	@Override
	@RequiredTx
	public void delete(Query query) {
		resourceRepository.delete(query);
	}

	@Override
	public Resource get(Query query) {
		return resourceRepository.get(query);
	}

	@Override
	public File toFile(Resource resource) {
		Long tenantId = resource.getTenantId();
		String path = resource.getPath();
		Long id = resource.getId();
		return Paths.get(getResourceLocation(), String.valueOf(tenantId), path, String.valueOf(id)).toFile();
	}

	private String getResourceLocation() {
		String resourceLocation = longanProperties.getResourceLocation();
		return resourceLocation + Const.SLASH + "upload";
	}

	@Override
	public List<Resource> list(Resource resource) {
		return resourceRepository.list(resource);
	}

}
